public class Solution {
    public int removeElement(int[] A, int elem) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int i = 0, j = A.length - 1;
        while (i <= j) {
            if (A[i] == elem) {
                if (A[j] == elem) {
                    j--; 
                } else {
                    A[i] = A[j];
                    i++;
                    j--; 
                }   
            } else {
                i++;
            }   
        }   
        return i;
    }
}

